import 'package:get/get.dart';

import '../../base/model.dart';
import '../../base/schema.dart';
import '../public/objects.dart';
import '../target/base/belong.dart';
import '../target/base/target.dart';
import '../thing/fileinfo.dart';
import 'index.dart';

/// 主页方法提供者
class HomeProvider {
  late String _userId;
  late DataProvider _data;
  late XObject<Xbase>? _cacheObj;
  late HomeConfig _homeConfig;
  late IBelong selectSpace;
  late HomeConfig2 homeConfig;
  late Map<String, List<IFileInfo>> cacheCommons;

  HomeProvider(DataProvider data) {
    _data = data;
    _userId = _data.user?.id ?? "";
    _cacheObj = _data.user?.cacheObj;
    selectSpace = _data.user!;
    _homeConfig = HomeConfig(lastSpaceId: _userId);
    homeConfig = HomeConfig2(tops: []);
    cacheCommons = new Map();
  }

  bool get isUser {
    return current.id == _userId;
  }

  List<IBelong> get spaces {
    if (null != _data.user) {
      return [_data.user!.user as IBelong, ..._data.user?.companys ?? []];
    } else {
      return [];
    }
  }

  IBelong get current {
    return selectSpace;
    // return spaces.firstWhereOrNull((i) => i.id == _homeConfig.lastSpaceId) ??
    //     _data.user as IBelong;
  }

  String commentsFlag(IBelong? belong) {
    belong = belong ?? current;
    return belong.id == _userId ? '_commons' : '_${belong.id}commons';
  }

  List<ITarget> targets(IBelong? belong) {
    belong = belong ?? current;
    return belong.id == _userId ? _data.targets : belong.targets;
  }

  void switchSpace(IBelong space) {
    selectSpace = space;
    _homeConfig.lastSpaceId = space.id;
    _cacheObj?.set('homeConfig', homeConfig);
  }

  Future<void> loadConfig() async {
    var cache = await _cacheObj?.getValue('homeConfig');
    if (null != cache) {
      homeConfig.tops = (cache as Map)['tops'];
    }
  }

  // Future<List<IFileInfo>> loadCommons(IBelong? belong) async {
  //   List<IFileInfo> files = [];
  //   belong = belong ?? current;
  //   belong.commons.forEach((item) async {
  //     var target = targets(belong).firstWhereOrNull(
  //         (i) => i.id == item.targetId && i.spaceId == item.spaceId);
  //     if (null != target) {
  //       var file = await target.directory.searchComment(item);
  //       if (null != file) {
  //         files.add(file);
  //       }
  //     }
  //   });
  //   return files;
  // }
}
